import os
import sys
import MySQLdb
import socket
import select
from generic import *

class server_router():
    def __init__(self):
        global sr_listen
        global descriptors
        global users_descriptors
        
        print  "Se inicia el servidor router"
        
        #-----------------------------------------------------------------------------------------------------------#
        #                      CARGA DEL ARCHIVO DE CONFIGURACION                                      #
        #-----------------------------------------------------------------------------------------------------------#
        try:
            file_conf = open('./config')
            self.dic = {}
            parsear_conf(file_conf,  self.dic)
            file_conf.close()
            print "Configuracion cargada exitosamente"
        except:
            print "Ejecute primero la configuracion"
        #-------------------------------------------
        
        #-----------------------------------------------------------------------------------------------------------#
        #                                            CARGA DE BASE DE DATOS                                               #
        #-----------------------------------------------------------------------------------------------------------#
        
        #  CONEXION A BASE DE DATOS #
        
        print "Se inicia la configuracion"
        print "Comprobando conexion a base de datos de servidores"
        db=MySQLdb.connect(host=str(self.dic["IP_Data_Base:"]),user='root',passwd='iamnicsee',db='servers')
        print "Se ha conectado a la base de datos de servidores exitosamente"
        print "Cerrando conexion a base de datos de servidores"
        db.close()
        print "Se ha cerrado exitosamente la conexion a la base de datos de servidores"
        
        
        
        #-----------------------------------------------------------------------------------------------------------#
        #                                      PREPARACION DE LA CONEXION                                          #
        #-----------------------------------------------------------------------------------------------------------#
        sr_listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sr_listen.bind(("", 8000))
        except:
            sr_listen.bind(("", 8001))
            print "Escuchando por el puerto 8001"
        sr_listen.listen(5)
        descriptors = [sr_listen]
        users_descriptors = {}
        while 1:
            self.accept_new_connection()
            (sread, swrite, sexc) = select.select(descriptors, [], [])
            for sock in sread:
                if sock != sr_listen:
                    flag = self.get_msg(sock)
                    if flag:
                        self.broadcast(flag, sock)


    def accept_new_connection(self):
        try:
            global sr_listen
            global descriptors
            global users_descriptors
            newsock, (remhost, remport) = sr_listen.accept()
            sr_listen.settimeout(1)
            address = str(remhost) + ':' + str(remport)
            print "Se ha conectado %s:%s" % (str(remhost), str(remport))
            descriptors.append(newsock)
            users_descriptors[newsock] = address
            print users_descriptors
        except:
            pass

    def broadcast(self,  msg, sock):

        global descriptors
        global sr_listen
        global users_descriptors
        host, port = sock.getpeername()
        msg = "[%s:%s]: %s" % (str(host), str(port), str(msg))
        print msg
        for destsock in descriptors:
            if destsock != sock and destsock != sr_listen:
                try:
                    destsock.send(msg)
                except:
                    print "Eliminando: " + str(users_descriptors[destsock])
                    descriptors.remove(destsock)
                    del users_descriptors[destsock]
                    print users_descriptors

    def get_msg(self,  sock):
        global users_descriptors
        try:
            msg = sock.recv(1024)
            sock.settimeout(.1)
            return msg
        except:
            global descriptors
            host, port = sock.getpeername()
            print "[%s:%s] ha salido." % (str(host), str(port))
            descriptors.remove(sock)
            return None
            

 
